package cp7_jstl_javabean.user;

import bean.UserInfo;
import util.DBTool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

// 查看所有用户的列表
@WebServlet("/cp7/user/list")
public class UserListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sql = "select * from userinfo";
        try {
            ResultSet rs = DBTool.executeQuery(sql); //
            // 需要传输所有的用户 所以需要创建集合进行保存
            List<UserInfo> list = new ArrayList<>();
            while(rs.next()){
                // 创建一个user对象
                UserInfo u = new UserInfo();
                // 读取结果
                u.setId(rs.getInt("id"));
                u.setNickname(rs.getString("nickname"));
                u.setStatus(rs.getInt("status"));
                u.setAccount(rs.getString("account"));
                u.setEmail(rs.getString("email"));
                u.setCreateTime(rs.getDate("create_time"));
                u.setHeaderImage(rs.getString("header_image"));
                u.setHeaderUrl(rs.getString("header_url"));
                u.setPassword(rs.getString("password"));
                u.setUpdateTIme(rs.getDate("update_time"));
                // 将对象添加到集合
                list.add(u);
            }
            // 关闭连接 但是下面的操作不好？
            Statement st = rs.getStatement();
            Connection conn = st.getConnection();
            DBTool.closeResultSet(rs);
            // 问题？从何获取statement
            DBTool.closeStatement(st);
            DBTool.closeConnection(conn);
            req.setAttribute("allUser",list);
            req.getRequestDispatcher("/cp7/list.jsp").forward(req,resp);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
